package com.wenjie.terminal;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Messenger;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.pantum.lld.DeviceManager;
import com.wenjie.terminal.config.App;
import com.wenjie.terminal.entity.HandlerMessage;
import com.wenjie.terminal.entity.enums.HandlerMessageType;
import com.wenjie.terminal.interfaces.PermissionResultService;
import com.wenjie.terminal.service.HttpServerService;
import com.wenjie.terminal.util.CLog;
import com.wenjie.terminal.util.PermissionUtil;
import com.wenjie.terminal.util.UsbDeviceUtil;

import java.io.File;

public class MainActivity extends AppCompatActivity {

    private ProgressBar progressBar;
    private TextView tipText;

    private Context context;

    private App app;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        context = this.getApplicationContext();
        app = (App) context;

        // 设置全屏
        Window window = getWindow();
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        // 隐藏导航栏和状态栏（沉浸式模式）
        window.getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // 隐藏导航栏
                        | View.SYSTEM_UI_FLAG_FULLSCREEN // 隐藏状态栏
                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY // 沉浸模式
        );

        setContentView(R.layout.activity_main);

        progressBar = findViewById(R.id.progress_circular);
        tipText = findViewById(R.id.tips);
    }

    @Override
    protected void onResume() {
        super.onResume();

        // 判断打印SDK是否初始化成功
        if (app.getPrintDevice() == null) {
            try {
                CLog.d("===> 打印SDK初始化...");

                boolean initResult = this.printSdkInit();
                if (!initResult) {
                    this.showTip("打印功能初始化失败，请重启应用再次尝试");
                    return;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                this.showTip("打印功能初始化失败，请重启应用再次尝试");
                return;
            }
        }

        // 检查权限
        PermissionUtil permissionUtil = new PermissionUtil(this);
        permissionUtil.checkPermission(this, new PermissionResultService() {
            @Override
            public void applyResult(boolean isSuccess, String message) {
                if (isSuccess) {
                    // 判断HTTP服务是否运行，如果正在运行先停止服务
                    if (isServiceRunning(HttpServerService.class)) {
                        Intent serviceIntent = new Intent(context, HttpServerService.class);
                        stopService(serviceIntent);
                    }

                    // 重启服务
                    Intent serviceIntent = new Intent(context, HttpServerService.class);

                    final Handler handler = initHttpMessageHandler();
                    Messenger messenger = new Messenger(handler);
                    serviceIntent.putExtra("handlerMessenger", messenger);

                    startForegroundService(serviceIntent);

                    // 获取所有的USB设备
                    UsbDeviceUtil.getAllUsbDevice(app);
                } else {
                    showTip(message);
                }
            }
        });
    }

    /**
     * 打印SDK初始化
     */
    private boolean printSdkInit() {
        Context aContext = app.getContext();

        File externalFilesDir = aContext.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
        if (externalFilesDir == null) {
            // 外部存储不可用，使用内部存储
            externalFilesDir = aContext.getFilesDir();
            CLog.e("===> 外部存储不可用，使用内部存储");
        }
        String fileSavePath = externalFilesDir.getAbsolutePath();

        // 打印SDK初始化
        DeviceManager printDevice = DeviceManager.getInstance();
        boolean initResult = printDevice.init(context, fileSavePath);
        if (initResult) {
            app.setPrintDevice(printDevice);
            CLog.d("打印机SDK初始化成功");
        } else {
            CLog.d("打印机SDK初始化失败");
        }

        return initResult;
    }

    /**
     * 显示提示信息
     */
    private void showTip(String message) {
        progressBar.setVisibility(View.INVISIBLE);
        tipText.setText(message);
    }

    /**
     * 初始化Http服务Handler
     */
    private Handler initHttpMessageHandler() {
        return new Handler(Looper.getMainLooper(), msg -> {
            HandlerMessage message = (HandlerMessage) msg.obj;

            final HandlerMessageType messageType = message.getMessageType();
            switch (messageType) {
                case TEXT_TIP: {
                    String text = message.getMessage();
                    this.showTip(text);

                    break;
                }

                case GO_WEB_VIEW: {
                    Intent intent = new Intent(MainActivity.this, WebViewActivity.class);
                    startActivity(intent);
                    break;
                }

                default: {
                    break;
                }
            }

            // 处理消息
            return true;
        });
    }

    /**
     * 检查指定的服务是否在运行
     *
     * @param serviceClass 服务的类
     * @return true 如果服务正在运行，否则 false
     */
    private boolean isServiceRunning(Class<?> serviceClass) {
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        if (activityManager != null) {
            // 获取所有正在运行的服务
            for (ActivityManager.RunningServiceInfo service : activityManager.getRunningServices(Integer.MAX_VALUE)) {
                if (serviceClass.getName().equals(service.service.getClassName())) {
                    // 服务正在运行
                    return true;
                }
            }
        }

        // 服务未运行
        return false;
    }
}